<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/14
 * Time: 16:06
 * 抓取单个Shipmentid
 */
namespace Inbound\Controller;
use \Home\Controller\CommonController;
use Inbound\Service\PublicInfoService;
class SingleShipmentidGrabController extends CommonController {
    public $singleShipmentidGrabService = NULL;
    public $Inboundshipmentplan = NULL;
    public $apiInbound         = NULL;
    public $accounts            = NULL;
    public $apiShipToAddress = NULL;
    public $apiAccounts = NULL;

    /**
     * 默认构造方法
     */
    public function __construct() {
        $this->singleShipmentidGrabService = D('SingleShipmentidGrab','Service');
        $this->Inboundshipmentplan = D('Inboundshipmentplan','Service');
        $this->apiInbound         = D('Api/Amazon/Inbound','Service');
        $this->apiShipToAddress   = D('Api/Amazon/ShipToAddress','Service');
        $this->apiAccounts   = D('Api/Amazon/Accounts','Service');
        parent::__construct();
    }

    /**
     * 抓取首页
     */
    public function index() {
        $this->assign('accounts', PublicInfoService::salesmanBindAccountsGet($_SESSION['current_account']['id']));
        $this->assign('transport_way', PublicInfoService::get_transport_way_array());
        $this->assign('enterprise_dominant', PublicInfoService::get_company_array());
        $this->display();
    }

    /**
     *平台计划单的抓取
     */
    public function grabShipmentid() {
        if(!empty($_POST['shipmentid']) && !empty($_POST['accountId'])) {
            $_POST['shipmentid'] = trim($_POST['shipmentid']);
            $this->condition = array(
                'account_id'=>$_POST['accountId'],
                'shipmentid'=>$_POST['shipmentid']
            );
            $shipmentidExist = $this->Inboundshipmentplan->get_field_by_param($this->condition, array('id'));
            if(empty($shipmentidExist)) {
                $inboundShipmentItems = $this->apiInbound->listInboundShipmentItems(
                    $_POST['accountId'],
                    array(
                        'ShipmentId' => $_POST['shipmentid'],
                    )
                );
                $inboundShipments = $this->apiInbound->listInboundShipments(
                    $_POST['accountId'],
                    array(
                        'ShipmentIdList' => $_POST['shipmentid'],
                    )
                );

                if(empty($inboundShipmentItems) || empty($inboundShipments) || !isset($inboundShipments[0][0]['DestinationFulfillmentCenterId'])) {
                    echo "<script>alert('亚马逊平台接口异常，可以将账号和Shipmentid发送给IT去排查原因');window.location.href='index'</script>";
                    exit;
                }

                $inboundShipments = $inboundShipments[0][0];

                $shipToAddress = $this->singleShipmentidGrabService->destinationFulfillmentCenterAddress(
                    $_POST['accountId'],
                    $inboundShipments['DestinationFulfillmentCenterId']
                );

                $shipmentItems = $this->singleShipmentidGrabService->matchNeedsApply($_POST['accountId'], $inboundShipmentItems);

            } else {
                echo "<script>alert('该平台计划单已经存在');window.location.href = 'index'</script>";
                exit;
            }
        } else {
            echo "<script>alert('请输入正确的账号和Shipmentid');window.location.href = 'index'</script>";
            exit;
        }
        $shipmentOk = $shipmentItems['ok'];
        $inboundShipments['site_id'] = $shipmentItems['site_id'];
        unset($shipmentItems['ok'], $shipmentItems['site_id']);

        $this->assign('shipmentOk', $shipmentOk);
        $this->assign('inboundShipments', $inboundShipments);
        $this->assign('shipToAddress', $shipToAddress);
        $this->assign('shipmentItems', $shipmentItems);
        $this->assign('accounts', PublicInfoService::salesmanBindAccountsGet($_SESSION['current_account']['id']));
        $this->assign('postData', $_POST);

        $shipmentOk && S(
            $_POST['accountId'] . '_' . $inboundShipments['ShipmentId'] . '_GRAB',
            array(
                'inboundShipments'=>$inboundShipments,
                'shipmentItems' => $shipmentItems,
                'shipToAddress' => $shipToAddress
            ),
            7200
        );

        $this->display('index');
    }

    /**
     * 单个Shipmentid抓取提交
     */
    public function grabSubmit() {
        $_POST['shipmentid'] = trim($_POST['shipmentid']);
        $grabShipmentidCache = S($_POST['accountId'] . '_' . $_POST['shipmentid'] . '_GRAB');
        $accountInfo = $this->apiAccounts->getAccountsByIds(array($_POST['accountId']));

        if(empty($accountInfo)) {
            echo json_encode(array('msg' => '当前账号异常'));
            exit;
        }
        if(empty($grabShipmentidCache)) {
            echo json_encode(array('msg' => '页面过期或者其他异常，请重新抓取'));
            exit;
        }

        /*出口退税和非出口退税不能放在一个shipmentid里*/
        $exportGroup = M("fba_prepare_needs_details", ' ', 'DB_FBAERP')
            ->where(array('id' => array('IN', $_POST['needsDetailIdStr'])))
            ->group('export_tax_rebate')
            ->getField('export_tax_rebate',TRUE);

        if(count($exportGroup) > 1) {
            echo json_encode(array('msg' => '应关务组（高玲玲、郑燚）和物流组（陈彦宇）要求，出口退税和非出口退税货物不能一起创建Shipmentid'));
            exit;
        }

        $inboundShipments = array();
        $inboundShipments['account_id'] = $_POST['accountId'];
        $inboundShipments['account_name'] = $accountInfo[$_POST['accountId']]['name'];
        $inboundShipments['merchant_id'] = $accountInfo[$_POST['accountId']]['merchant_id'];
        $inboundShipments['site_id'] = $grabShipmentidCache['inboundShipments']['site_id'];
        $inboundShipments['shipmentid'] = $grabShipmentidCache['inboundShipments']['ShipmentId'];
        $inboundShipments['seller_id'] = $_SESSION['current_account']['id'];
        $inboundShipments['shipment_name'] = $grabShipmentidCache['inboundShipments']['ShipmentName'];
        $inboundShipments['tranfer_hopper_id'] = 1;
        if(isset($_POST['pushWarehouseFlag']) && $_POST['pushWarehouseFlag']) {
            $inboundShipments['status'] = 15;
            $inboundShipments['push_warehouse_user_id'] = $_SESSION['current_account']['id'];
            $inboundShipments['push_warehouse_time'] = date("Y-m-d H:i:s");
        } else {
            $inboundShipments['status'] = 10;
        }
        $inboundShipments['ship_from_address_id'] = $grabShipmentidCache['inboundShipments']['ship_from_address_id'];
        $inboundShipments['destination_fullfillment_center_id'] = $grabShipmentidCache['inboundShipments']['DestinationFulfillmentCenterId'];
        if(empty($grabShipmentidCache['shipToAddress'])) {
            $shipToAddressData = array();
            $shipToAddressData['site_id'] = $grabShipmentidCache['inboundShipments']['site_id'];
            $shipToAddressData['CenterId'] = $grabShipmentidCache['inboundShipments']['DestinationFulfillmentCenterId'];
            $shipToAddressData['amazon_address_dec'] = trim($_POST['shipToAddressDec']);

            $inboundShipments['ship_to_address_id'] = $this->apiShipToAddress->getOrInsertShipToAddress($_POST['accountId'], $shipToAddressData);
        } else {
            $inboundShipments['ship_to_address_id'] = $grabShipmentidCache['shipToAddress']['id'];
        }

        $inboundShipments['create_user_id'] = $_SESSION['current_account']['id'];
        $inboundShipments['create_time'] = date("Y-m-d H:i:s");
        $inboundShipments['remark'] = trim($_POST['remark']);
        $inboundShipments['ship_from_address_id'] = $grabShipmentidCache['inboundShipments']['ship_from_address_id'];

        $inboundShipmentItems = $claimArriveDate = array();
        foreach ($grabShipmentidCache['shipmentItems'] as $item) {
            $currentNeedDetailId = array_intersect($item['connectNeedsDetailId'], $_POST['needsDetailIdStr']);
            if(!empty($currentNeedDetailId)) {
                $singleItem = array();
                $singleItem['needDetailId'] = current($currentNeedDetailId);
                $singleItem['sku'] = $item['sku'];
                $singleItem['sku_name'] = $item['sku_name'];
                $singleItem['seller_sku'] = $item['seller_sku'];
                $singleItem['fnsku'] = $item['fnsku'];
                $singleItem['title'] = $item['title'];
                $singleItem['quantity'] = $item['quantity'];
                $singleItem['export_tax_rebate'] = $item['radios'][$singleItem['needDetailId']]['export_tax_rebate'];
                $singleItem['enterprise_dominant'] = $item['radios'][$singleItem['needDetailId']]['enterprise_dominant'];
                $claimArriveDate[] = $item['radios'][$singleItem['needDetailId']]['claim_arrive_time'];
                $singleItem['hs_code'] = $item['hs_code'];
                $singleItem['declaration_element'] = $item['declaration_element'];
                $singleItem['sku_cname'] = $item['sku_cname'];

                $inboundShipmentItems[] = $singleItem;
            }
        }
        //根据明细的要求到货日期推断平台计划单的最早的要求到货日期
        $inboundShipments['claim_arrive_time'] = min($claimArriveDate);

        $status = $this->singleShipmentidGrabService->addGrabShipmentid($inboundShipments, $inboundShipmentItems);

        if ($status == 200) {
            echo json_encode(array('msg' => '操作成功'));
            exit;
        }
    }
}